﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Top.Web;
using Top.Web.Api;
using Top.PointStore.Business;
using Top.Web.Api.Filters;
using Top.Business.OAuth;

namespace Top.PointStore.Web.Controllers
{
    public class ExternalVisitController : ApiBase
    {
        [NoLogin]
        public async Task<object> Visit(Guid accesstoken = default(Guid))
        {
            OAuthUser oauthUser = null;
            if (accesstoken != default(Guid))
            {
                oauthUser = OAuthHelper.GetUserByAk(accesstoken.ToString());
                User = oauthUser;
            }

            if (User != null && User.IsAuthenticated == true)
            {
                return Redirect("/admin/sreach.html");
            }
            else
            {
                //return Redirect("http://crm.point.tops001.com/admin/Login_FromOA.html");
                return Redirect("../admin/Login_FromOA.html");
                //return Redirect("http://localhost:8624/admin/Login_FromOA.html");                
            }
        }

        [Login]
        public async Task<object> VisitPointStore(string url, string city="",string ip="",string tag="",string beforeUrl="")
        {
            string userToken = User.UserToken.ToString();
            ip = GetHostAddress();
            await ExternalVisitManager.Insert(userToken, ip, tag, url, beforeUrl, city);
            return 1;
        }

        //------------------------------------------------一些用到的方法-----------------------------------------------------

        /// <summary>
        /// 获取客户端IP地址（无视代理）
        /// </summary>
        /// <returns>若失败则返回回送地址</returns>
        public static string GetHostAddress()
        {
            string userHostAddress = Top.Web.Api.WebApiContext.Current.WebApi.UserHostAddress;

            //最后判断获取是否成功，并检查IP地址的格式（检查其格式非常重要）
            if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
            {
                return userHostAddress;
            }
            return "127.0.0.1";
        }

        /// <summary>
        /// 检查IP地址格式
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
    }
}